package com.flushbonading.controller;


import com.auth0.jwt.JWT;
import com.flushbonading.annotation.BackStage;
import com.flushbonading.pojo.User;
import com.flushbonading.pojo.dto.UserMessageDTO;
import com.flushbonading.service.impl.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zyx&zyx
 * @since 2021-04-08
 */
@RestController
@RequestMapping("/user")
@BackStage
@Api(tags = "用户接口")
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private StudentServiceImpl studentService;
    @Autowired
    private TeacherServiceImpl teacherService;
    @Autowired
    private RegistrationServiceImpl registrationService;
    @Autowired
    private RoleServiceImpl roleService;

    @ApiOperation("通过登录的账号得到用户相关信息")
    @PostMapping("/userMessage")
    public UserMessageDTO getUserMessage(final HttpServletRequest request) {
        final String token = request.getHeader("token");
        final String user_id = JWT.decode(token).getAudience().get(0);
        System.out.println(user_id);
        //获取user对象
        final User role = this.userService.getRoleByUserId(user_id);
        //得到role中的nature字段
        final String nature = role.getNature();
        System.out.println(nature);
        //拿到role中的role_id
        final int roleID = role.getRole_id();
        final String roleName = this.roleService.getNameByRoleId(roleID);
        String name = null;
        if (nature.equals("teacher")) {
            //到teacher表中查找名字
            name = this.teacherService.getNameByTeacherId(user_id);
            System.out.println(name);
        } else if (nature.equals("student")) {
            //到student表中查找
            name = this.studentService.getNameByStudnetNum(user_id);
        } else {
            //到registration表中查找名字
            name = this.registrationService.getNameByStudentNum(user_id);
        }
        //构造对象
        final UserMessageDTO userMessage = UserMessageDTO.builder()
                .name(name)
                .roleName(roleName)
                .build();
        System.out.println(userMessage);
        return userMessage;
    }
}
